import { login } from '@/api/employeeApi'; // 导入封装好的登录API

export default {
    data() {
        return {
            loginForm: {
                username: '',
                password: ''
            }
        };
    },
    methods: {
        async submitClick() {
            // 1. 表单验证
            if (this.loginForm.username === '' || this.loginForm.password === '') {
                this.$alert('账号或密码不能为空', '提示', { confirmButtonText: '确定' });
                return;
            }
            if (this.loginForm.username.length < 6 || this.loginForm.password.length < 6) {
                this.$alert('账号和密码必须大于6位', '提示', { confirmButtonText: '确定' });
                return;
            }

            // 2. 调用封装好的API
            try {
                const result = await login(this.loginForm.username, this.loginForm.password);

                if (result.code === 200) {
                    this.$alert('登录成功', '提示', {
                        confirmButtonText: '确定'
                    }).then(() => {
                        // 3. 存储用户信息到sessionStorage
                        window.sessionStorage.setItem('empId', result.data.employeeId);
                        window.sessionStorage.setItem('account', result.data.account);
                        window.sessionStorage.setItem('name', result.data.employeeName);
                        window.sessionStorage.setItem('role', result.data.role);

                        // 4. 跳转到首页
                        this.$router.replace({ name: '欢迎界面' });
                    });
                } else {
                    this.$alert(result.message || '账号或密码错误', '提示', {
                        confirmButtonText: '确定'
                    });
                }
            } catch (error) {
                console.error('登录失败:', error);
                this.$alert('网络错误，请稍后再试', '提示', {
                    confirmButtonText: '确定'
                });
            }
        }
    }
};